﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Xml;
using Blazing.Web.Util;
using System.Web.Configuration;
using Blazing.WebFacade;
using Blazing.BusinessObjects.Queries;
using Blazing.BusinessObjects.Tagging;
using Blazing.BusinessObjects.Cms;

namespace Blazing.Web.Handlers
{
    public class RssHandler : IHttpHandler
    {
        #region IHttpHandler Members

        public bool IsReusable
        {
            get { return false; }
        }

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/xml";

            if (context.Request.QueryString["tagslug"] != null)
            {
                string tagslug = context.Request.QueryString["tagslug"];

                XmlTextWriter writer = new XmlTextWriter(context.Response.Output);
                writer.Formatting = Formatting.Indented;

                string hostUrl = context.Request.Url.Host;

                //if test app
                if (WebConfigurationManager.AppSettings["TestMode"] == "True")
                    hostUrl = WebConfigurationManager.AppSettings["TestSite"];

                SiteController siteCon = new SiteController();
                Site _site = siteCon.GetSite(hostUrl);
                if (_site != null)
                {
                    RssFeedWriter feed = new RssFeedWriter();
                    PageController pagecontroller = new PageController();
                    SettingsController settings = new SettingsController();
                    IList<TaxonomyTag> tags = TaxonomyTag.Search(QrySearchTaxonomyTagsBySlugs.Query(new List<string> { tagslug }));
                    IList<Contentpage> items = pagecontroller.GetPages(_site, tags, 10);

                    List<Contentpage> sorted = new List<Contentpage>(items);
                    //reverse normal sorting order to get the newest first
                    sorted.Reverse();

                    feed.WriteFeed(writer, items, tags[0].Description, context.Request.Url.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped), "", "");                        
                }
            }
            else
            {
                context.Response.StatusCode = 404;
            }
        }

        #endregion
    }
}
